<template>
  <div class="chart">
    <div class="head">
      <div class="title">
        <h3>销售数据</h3>
        <span>{{ start }} ~ {{ week.end }}</span>
      </div>
      <div class="week-month-year">
        <div
          v-for="(it,i) in btns"
          :key="i"
          class="item"
          :class="{ischecked:cur === i}"
          @click="change(i)"
        >{{ it }}</div>
      </div>
    </div>
    <div class="show">
      <!-- 折线图 -->
      <div ref="line" class="lef">111</div>
      <!-- 柱状图 -->
      <div v-show="show" ref="bar" class="rig">222</div>
      <div v-show="!show" class="empty rig">
        <img src="https://likede2-admin.itheima.net/img/empty.87c4f71b.png" alt>
        <div class="tips">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mapActions, mapState } from 'vuex'
import moment from 'moment'
export default {
  name: 'EchartShow',
  data() {
    // 获取当前周周一日期
    function getMonDay() {
      const now = new Date()
      const nowTime = now.getTime()
      const day = now.getDay() === 0 ? 7 : now.getDay()
      const oneDayTime = 24 * 60 * 60 * 1000
      const monDay = nowTime - (day - 1) * oneDayTime
      return moment(monDay).format('YYYY-MM-DD')
    }
    return {
      btns: ['周', '月', '年'],
      cur: 0,
      show: false,
      start: getMonDay(),
      week: {
        start: getMonDay(),
        end: moment().format('YYYY-MM-DD')
      },
      month: {
        start: moment().format('YYYY-MM') + '-01',
        end: moment().format('YYYY-MM-DD')
      },
      year: {
        start: moment().format('YYYY') + '-01-01',
        end: moment().format('YYYY-MM-DD')
      }
    }
  },
  computed: {
    ...mapState('home', ['amountInfo', 'regionInfo'])
  },
  watch: {
    amountInfo: {
      immediate: true,
      handler(newVal) {
        this.$nextTick(() => {
          // 先调用echarts.getInstanceByDom()方法判断是否已经存在echarts实例，如果不存在再去初始化
          // 有的话就获取已有echarts实例的DOM节点
          let lineChart = echarts.getInstanceByDom(this.$refs.line)
          // 如果不存在，就进行初始化
          if (lineChart == null) {
            lineChart = echarts.init(this.$refs.line)
          }
          // 绘制图表
          lineChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            title: {
              left: 'center',
              text: '销售趋势图'
            },
            grid: {
              left: '3%',
              right: '5.5%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: newVal.xAxis
            },
            yAxis: {
              type: 'value',
              name: '单位：元'
            },
            series: [
              {
                data: newVal.series ? newVal.series.map(it => it / 100) : [],
                type: 'line',
                smooth: true,
                itemStyle: {
                  color: 'rgb(220, 70, 70)'
                },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: 'rgba(220, 70, 70,0.3)'
                    },
                    {
                      offset: 1,
                      color: 'rgba(220, 70, 70,0)'
                    }
                  ])
                }
              }
            ]
          })
        })
      }
    },
    regionInfo: {
      immediate: true,
      handler(newVal) {
        try {
          if (newVal.series.length > 0) {
            this.show = true
            this.$nextTick(() => {
              let barChart = echarts.getInstanceByDom(this.$refs.bar)
              if (barChart == null) {
                barChart = echarts.init(this.$refs.bar)
              }
              barChart.setOption({
                tooltip: {
                  trigger: 'axis'
                },
                title: {
                  left: 'center',
                  text: '销售额分布'
                },
                grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true
                },
                xAxis: {
                  type: 'category',
                  data: newVal.xAxis
                },
                yAxis: {
                  type: 'value',
                  name: '单位：元'
                },
                series: [
                  {
                    data: newVal.series ? newVal.series.map(it => it / 100) : [],
                    type: 'bar',
                    itemStyle: {
                      color: '#91B0FF'
                    },
                    barWidth: '15'
                  }
                ]
              })
            })
          } else {
            this.show = false
          }
        } catch (error) {
          this.show = false
        }
      }
    }
  },
  async created() {
    await this.getAmountInfo({
      type: 1,
      ...this.week
    })
    await this.getRegionInfo(this.week)
  },
  methods: {
    ...mapActions('home', ['getAmountInfo', 'getRegionInfo']),
    async change(i) {
      this.cur = i
      switch (this.cur) {
        case 0:
          this.start = this.week.start
          await this.getAmountInfo({
            type: 1,
            ...this.week
          })
          await this.getRegionInfo(this.week)
          break
        case 1:
          this.start = this.month.start
          await this.getAmountInfo({
            type: 1,
            ...this.month
          })
          await this.getRegionInfo(this.month)
          break
        case 2:
          this.start = this.year.start
          await this.getAmountInfo({
            type: 2,
            ...this.year
          })
          await this.getRegionInfo(this.year)
          break
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.chart {
  width: 100%;
  height: 352px;
  background-color: #fff;
  padding: 20px;
  transform: translateY(20px);
  border-radius: 20px;
  .head {
    display: flex;
    justify-content: space-between !important;
    align-items: center;
    .title {
      align-items: center;
      margin-bottom: 0;
    }
    .week-month-year {
      display: flex;
      justify-content: space-evenly !important;
      align-items: center;
      background: rgba(233, 243, 255, 0.37);
      border-radius: 8px;
      width: 129px;
      height: 34px;
      .item {
        width: 37px;
        height: 25px;
        line-height: 25px;
        font-size: 14px;
        color: #9ca3b4;
        cursor: pointer;
        border-radius: 5px;
        text-align: center;
        &.ischecked {
          background-color: #fff;
          color: #333;
        }
      }
    }
  }
  .show {
    width: 100%;
    height: 278px;
    display: flex;
    .lef,
    .rig {
      flex: 1;
    }
  }
}
</style>
